VERSION 0.6
ARG DOCKERHUB_USER_SECRET=+secrets/DOCKERHUB_USER
ARG DOCKERHUB_TOKEN_SECRET=+secrets/DOCKERHUB_TOKEN
ARG DOCKERHUB_MIRROR
ARG DOCKERHUB_MIRROR_INSECURE=false
ARG DOCKERHUB_AUTH=true

ARG REGISTRY
ARG REGISTRY_IP
ARG EARTHLY_BUILD_ARGS="REGISTRY"
ARG REGISTRY_CONFIG="
[registry.\"$REGISTRY\"]
  http = true
  insecure = true
"

certs:
    FROM alpine:3.15
    RUN apk add openssl
    RUN openssl version
    RUN mkdir -p certs
    RUN (echo "[req]"; \
            echo distinguished_name=req; \
            echo "[san]"; \
            echo subjectAltName=DNS:registry,IP:$REGISTRY_IP \
            ) >./san.config
    RUN openssl req -x509 -newkey rsa:4096 -sha256 -days 3650 -nodes \
        -keyout certs/domain.key -out certs/domain.crt \
        -extensions san -config ./san.config \
        -subj "/CN=registry"
    SAVE ARTIFACT certs AS LOCAL certs

test-base:
    FROM ../..+earthly-integration-test-base \
        --DOCKERHUB_AUTH=$DOCKERHUB_AUTH \
        --DOCKERHUB_USER_SECRET=$DOCKERHUB_USER_SECRET \
        --DOCKERHUB_TOKEN_SECRET=$DOCKERHUB_TOKEN_SECRET \
        --DOCKERHUB_MIRROR=$DOCKERHUB_MIRROR \
        --DOCKERHUB_MIRROR_INSECURE=$DOCKERHUB_MIRROR_INSECURE
    WORKDIR /test
    COPY ./certs/domain.crt /etc/config/test.ca
    COPY test.earth ./Earthfile

all:
    BUILD +test-push-pull
    BUILD +test-connect

test-push-pull:
    FROM +test-base
    # Running with tmpfs mount = no local cache.
    DO +DO_REMOTE_CACHE_EARTHLY --target=+test-push
    DO +DO_REMOTE_CACHE_EARTHLY --target=+test-pull

test-connect:
    FROM +test-base
    COPY ./certs/domain.crt ./test.ca
    DO +DO_REMOTE_CACHE_EARTHLY --target=+test-connect

# Work around the lack of variable overriding, since the base image already includes EARTHLY_ADDITIONAL_BUILDKIT_CONFIG
DO_REMOTE_CACHE_EARTHLY:
    COMMAND

    ARG EARTHLY_ADDITIONAL_BUILDKIT_CONFIG
    ARG REGISTRY_CONFIG
    ARG target

    RUN --privileged \
        --mount=type=tmpfs,target=/tmp/earthly \
        -- \
        EARTHLY_ADDITIONAL_BUILDKIT_CONFIG=$EARTHLY_ADDITIONAL_BUILDKIT_CONFIG$REGISTRY_CONFIG \
        /usr/bin/earthly-entrypoint.sh --ci --push \
            --build-arg REGISTRY=$REGISTRY \
            --build-arg DOCKERHUB_AUTH=$DOCKERHUB_AUTH \
            --build-arg DOCKERHUB_USER_SECRET=$DOCKERHUB_USER_SECRET \
            --build-arg DOCKERHUB_TOKEN_SECRET=$DOCKERHUB_TOKEN_SECRET \
            --build-arg DOCKERHUB_MIRROR=$DOCKERHUB_MIRROR \
            --build-arg DOCKERHUB_MIRROR_INSECURE=$DOCKERHUB_MIRROR_INSECURE \
            $target 2>&1 | tee ./output
